﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.Platform.Core.UI.Controls;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Charting;
using Baosight.Platform.Core;
using Baosight.Platform.Core.ServiceModel;
using Baosight.ZNH.ZMCA.UI.Utils;
using Baosight.ZNH.ZMCA.UI.Model;
using Baosight.ZNH.ZMCommon;

namespace Baosight.ZNH.ZMCA.UI
{
    public partial class ZMCA23 : EFViewCmes
    {
        public ZMCA23()
        {
            InitializeComponent();
            InitControls();
        }

        private void InitControls()
        {
            List<EIRow> lstDataType = new List<EIRow>();

            EIRow r = new EIRow();
            r.Add("Name", "安全隐患");
            r.Add("Value", "2");
            lstDataType.Add(r);

            r = new EIRow();
            r.Add("Name", "生产三违");
            r.Add("Value", "1");
            lstDataType.Add(r);

            ddDataType.BindItemsToGrid(lstDataType, "Name");


            TrendChart.DefaultView.ChartArea.ItemClick += new EventHandler<ChartItemClickEventArgs>(ChartArea_ItemClick);
            Common.ClearChart(TrendChart);
            Common.ClearChart(PieChart);
        }

        private void InitPieChart()
        {
            //分布图
            Common.ClearChart(PieChart);
            PieChart.DefaultView.ChartTitle.Content = "单位分布";
            PieChart.DefaultView.ChartLegend.Header = "";
            PieChart.DefaultView.ChartLegendPosition = Telerik.Windows.Controls.Dock.Bottom;
            SeriesMapping smPie = new SeriesMapping();
            PieSeriesDefinition totalPie = new PieSeriesDefinition();
            smPie.SeriesDefinition = totalPie;
            //sm2.LegendLabel = "单位";
            smPie.ItemMappings.Add(new ItemMapping("XCategory", DataPointMember.XCategory));
            smPie.ItemMappings.Add(new ItemMapping("YValue", DataPointMember.YValue));
            smPie.ItemMappings.Add(new ItemMapping("LegendLabel", DataPointMember.LegendLabel));

            totalPie.InteractivitySettings.HoverScope = InteractivityScope.Item;
            totalPie.InteractivitySettings.SelectionScope = InteractivityScope.Item;
            totalPie.InteractivitySettings.SelectionMode = ChartSelectionMode.Single;
            totalPie.LegendDisplayMode = LegendDisplayMode.DataPointLabel;

            PieChart.SeriesMappings.Add(smPie);
        }

        private void InitTrendChart()
        {
            //趋势图
            TrendChart.SeriesMappings.Clear();
            TrendChart.DefaultView.ChartTitle.Content = "安全问题趋势";
            TrendChart.DefaultSeriesDefinition.ShowItemToolTips = true;
            TrendChart.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.None;
            TrendChart.DefaultView.ChartLegend.Visibility = System.Windows.Visibility.Collapsed;
            TrendChart.DefaultView.ChartLegend.Header = "";
            TrendChart.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            TrendChart.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            TrendChart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;

            SeriesMapping smBar = new SeriesMapping();
            BarSeriesDefinition totalBar = new BarSeriesDefinition();
            smBar.SeriesDefinition = totalBar;
            smBar.CollectionIndex = 0;
            smBar.LegendLabel = "问题总数";
            smBar.SeriesDefinition.ShowItemLabels = false;
            smBar.SeriesDefinition.ShowItemToolTips = true;
            smBar.SeriesDefinition.ShowZeroValuesLabels = true;
            smBar.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
            smBar.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));
            smBar.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
            smBar.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
            smBar.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;
            TrendChart.SeriesMappings.Add(smBar);

            SeriesMapping smSpline = new SeriesMapping();
            SplineSeriesDefinition totalSpline = new SplineSeriesDefinition();
            smSpline.SeriesDefinition = totalSpline;
            smSpline.CollectionIndex = 0;
            smSpline.LegendLabel = "问题总数";
            smSpline.SeriesDefinition.ShowItemLabels = false;
            smSpline.SeriesDefinition.ShowItemToolTips = true;
            smSpline.SeriesDefinition.ShowZeroValuesLabels = true;
            smSpline.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
            smSpline.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));
            smSpline.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
            smSpline.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
            smSpline.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;
            TrendChart.SeriesMappings.Add(smSpline);
        }

        public void OnQueryButtonClick(object sender, RoutedEventArgs e)
        {
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA23");
            eiInfo.Set("method", "queryByTrend");



            IList<CheckBox> selectedDataType = ddDataType.LstCheckedItems;
            string dataType = "''";
            foreach (var item in selectedDataType)
            {
                dataType = dataType + ",'" + (item.DataContext as EIRow)["Value"].ToString() + "'";
            }

            EIBlock conBlock = eiInfo.AddBlock("inqu_status");
            Common.AddEIColumnsToEIBlock(conBlock, new string[] { "fdToDate", "fdFromDate", "fdDataType" });
            EIRow conRow = new EIRow();
            conRow.Add("fdFromDate", datePicker.FromDate.ToString(Common.DateTimeFormatDate));
            conRow.Add("fdToDate", datePicker.ToDate.ToString(Common.DateTimeFormatDate));
            conRow.Add("fdDataType", dataType);
            conBlock.AddRow(conRow);

            TrendChart.Tag = conRow;
            Common.ClearChart(TrendChart);
            Common.ClearChart(PieChart);
            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, queryByTrendCompleted);

            (sender as Button).IsEnabled = false;
            TempButton = sender as Button;
        }

        private void queryByTrendCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo eiInfo = e.EIInfo;
            EIBlock resultBlock = eiInfo.GetBlock("result");
            if (resultBlock.Rows.Count <= 0)
            {
                Common.Alert("没有找到数据");
                base.TempButtonOpen(true);
                return;
            }

            InitTrendChart();
            TrendChart.ItemsSource = null;

            List<List<ChartData>> itemsSource = new List<List<ChartData>>();
            List<ChartData> totalList = new List<ChartData>();

            foreach (var item in resultBlock.Rows)
            {
                string date = item["fdDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }
                
                AddChartDate(item, date, totalList);
            }
            itemsSource.Add(totalList);

            TrendChart.ItemsSource = itemsSource;
            base.TempButtonOpen(true);
        }


        private static void AddChartDate(EIRow item, string date, List<ChartData> tList)
        {
            string year = date.Substring(0,4);
            string month = date.Substring(5);
            if (date[5] == '0')
            {
                month = date.Substring(6);
            }

            ChartData cd = new ChartData(year + "年" + month + "月", decimal.Parse(item["fdKeyId"].ToString()));
            cd.ShortDate = date;
            tList.Add(cd);
        }


        void ChartArea_ItemClick(object sender, ChartItemClickEventArgs e)
        {
            //selectedData格式为yyyy-MM
            ChartData selectedData = e.DataPoint.DataItem as ChartData;

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA23");
            eiInfo.Set("method", "queryByPie");

            EIBlock conBlock = eiInfo.AddBlock("inqu_status");
            //fdDepartmentId代表数据所在月份
            Common.AddEIColumnsToEIBlock(conBlock, new string[] { "fdFromDate", "fdToDate", "fdDataType", "fdDate" });
            EIRow conRow = TrendChart.Tag as EIRow;
            conRow.Add("fdDate", selectedData.ShortDate);
            conBlock.AddRow(conRow);

            PieChart.Tag = selectedData.DataValue;
            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, queryByPieCompleted);
        }

        private void queryByPieCompleted(object sender, DoWorkCompletedEventArgs e)
        {

            InitPieChart();
            EIInfo eiInfo = e.EIInfo;
            EIBlock resultBlock = eiInfo.GetBlock("result");

            //List<List<DataPoint>> itemsSource = new List<List<DataPoint>>();
            List<DataPoint> totalList = new List<DataPoint>();

            int departmentCount = 1;
            int totalForTop5Department = 0;
            foreach (var item in resultBlock.Rows)
            {
                string date = item["fdDepartmentId"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                DataPoint dp = new DataPoint();
                dp.YValue = Common.GetIntValue(item["fdKeyId"]);
                totalForTop5Department += Common.GetIntValue(item["fdKeyId"]);
                dp.XCategory = Common.GetStringValue(item["displayName"]);
                dp.LegendLabel = Common.GetStringValue(item["displayName"]);

                totalList.Add(dp);

                departmentCount++;
                if (departmentCount > 5)
                {
                    break;
                }
            }
            if (resultBlock.Rows.Count > 5)
            {
                DataPoint dp = new DataPoint();
                dp.YValue = Common.GetIntValue(PieChart.Tag) - totalForTop5Department;
                dp.XCategory = "其他";
                dp.LegendLabel = "其他";
                totalList.Add(dp);
            }

            //itemsSource.Add(totalList);


            //PieChart.SeriesMappings.Clear();
            PieChart.ItemsSource = null;
            PieChart.ItemsSource = totalList;
        }
    }
}
